package com.wl.api.controller.system;

import java.util.Date;
import java.util.Objects;
import java.util.function.Predicate;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.wl.api.common.annotation.RequiresAuthentication;
import com.wl.api.common.utils.BeanUtils;
import com.wl.api.common.utils.ErrorCodeEnum;
import com.wl.api.common.utils.JsonObject;
import com.wl.api.common.utils.StringUtil;
import com.wl.api.common.utils.constant.AppEnum;
import com.wl.api.controller.base.CommonController;
import com.wl.api.dto.base.CommonUserDTO;
import com.wl.api.dto.system.SecurityUserDTO;
import com.wl.api.model.system.SecurityUser;
import com.wl.api.service.system.ISecurityUserService;

/**
 * 
 * @author chenj
   @desc 接口安全通过 注解指定改方法安全
 *
 */
@RestController
@RequestMapping("/manage/system/user")
@RequiresAuthentication(getClientType = AppEnum.admin_client, getAuthticationSn="user")
public class SystemUserController extends CommonController {
	@Autowired
	ISecurityUserService userService;
	
	@RequestMapping(value="/create", method=RequestMethod.POST)
	@ResponseBody
	public JsonObject createSystemUser(@RequestBody SecurityUserDTO user)  throws Exception {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "" , error_code = ""; 
		if (validate().and(s -> StringUtil.isNotEmpty(s.getPassword())).negate().test(user)) {
			title = ErrorCodeEnum.param_error.getMessage();
			error_code = ErrorCodeEnum.param_error.getError_code();
			pass = false;
		}
		if (pass) {
			initUserData(user);
			SecurityUser entity = BeanUtils.copyProperties(user, SecurityUser.class);
			userService.insert(entity);
			json.setData(entity.getId());
		}
		setJsonMessage(json, title, error_code, pass);
		return json;
	}
	
	
	
	@RequestMapping(value = "/create", method = RequestMethod.PUT)
	@ResponseBody
	public JsonObject modifyUser(@RequestBody SecurityUserDTO user) throws Exception {
		JsonObject json = JsonObject.getInstance();
		boolean pass = true;
		String title = "" , error_code = ""; 
		if (validate().and(s -> s.getId() != null).negate().test(user)) {
			title = ErrorCodeEnum.param_error.getMessage();
			error_code = ErrorCodeEnum.param_error.getError_code();
			pass = false;
		}
		
		if (pass) {
			initUserData(user);
			user.setPassword(null);
			//user.setPassword(DigestUtils.md2Hex(user.getPassword()));
			SecurityUser entity = BeanUtils.copyProperties(user, SecurityUser.class);
			userService.updateById(entity);
			json.setData(entity.getId());
		}
		setJsonMessage(json, title, error_code, pass);
		return json;
	}
	
	@RequestMapping(value = "/pass", method = RequestMethod.PUT)
	public JsonObject modifyPass(SecurityUserDTO param) throws Exception {
		JsonObject json = JsonObject.getInstance();
		CommonUserDTO user = getCommonUser();
		boolean pass = true;
		String title = "", code = "";
		if (StringUtil.isEmpty(param.getUsername()) || StringUtil.isEmpty(param.getRealname()) ||
				StringUtil.isEmpty(param.getPassword()) || StringUtil.isEmpty(param.getOldpass()) || !Objects.equals(user.getUsername(), param.getUsername())) {
			pass = false;
			title = ErrorCodeEnum.param_error.getMessage();
			code = ErrorCodeEnum.param_error.getError_code();
		}
		if (pass && userService.getUserMessage(SecurityUserDTO.builder().username(param.getUsername()).password(DigestUtils.md2Hex(param.getOldpass())).build())== null) {
			title = ErrorCodeEnum.login_fail_account_error.getMessage();
			code = ErrorCodeEnum.login_fail_account_error.getError_code();
			pass = false;
		}
		if (pass) {
			userService.updateById(SecurityUser.builder().password(DigestUtils.md2Hex(param.getPassword())).id(user.getId()).build());
			json.setData(user.getId());
		}
		setJsonMessage(json, title, code, pass);
		return json;
	}
	
	@RequestMapping(value = "/create/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public JsonObject deletedUser(@PathVariable("id") Integer id) throws Exception {
		JsonObject json = JsonObject.getInstance();
		SecurityUser entity = SecurityUser.builder().isDeleted(1).id(new Long(id)).build();
		initUserVoData(entity);
		userService.updateById(entity);
		json.setData(id);
	 	setJsonMessage(json);
		return json;
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	@ResponseBody
	public JsonObject getUserList(String username, Integer id, String realname) {
		JsonObject json = JsonObject.getInstance();
		json.setData(userService.getUserPageList(SecurityUserDTO.builder().username(username).realname(realname).id(id == null ? null: new Long(id)).build()));
		setJsonMessage(json);
		return json;
	}
	
	@RequestMapping(value = "/create/{id}", method = RequestMethod.GET)
	@ResponseBody
	public JsonObject getUserDetail(@PathVariable("id")Integer id) {
		JsonObject json = JsonObject.getInstance();
		SecurityUserDTO user = userService.getUserMessage(SecurityUserDTO.builder().id(new Long(id)).isDeleted(0).build());
		clearUserData(user);
		json.setData(user);
		setJsonMessage(json);
		return json;
	}
	
	private void clearUserData(SecurityUserDTO user) {
		if (Objects.isNull(user)) {
			return ;
		}
		user.setIsDeleted(null);
		user.setStatus(null);
	}
	private void initUserData(SecurityUserDTO user) throws Exception {
		CommonUserDTO userDTO = getCommonUser();
		user.buildMsg(0, userDTO.getId());
	}
	
	private void initUserVoData(SecurityUser user) throws Exception {
		CommonUserDTO userDTO = getCommonUser();
		user.setUpdateId(userDTO.getId());
		user.setUpdateTime(new Date());
	}
	
	private Predicate<SecurityUserDTO> validate() {
		return s -> StringUtil.isNotEmpty(s.getUsername()) && StringUtil.isNotEmpty(s.getRealname())
				 && StringUtil.isNotEmpty(s.getPhone()) && StringUtil.isEmail(s.getEmail());
	}
	
}
